/*
 * Copyright (C) 2018 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xuexiang.xdlinkdemo.device.resolver;

import com.xuexiang.xdlink.component.resolver.impl.AbstractMessageResolver;
import com.xuexiang.xdlink.exception.ResolverException;
import com.xuexiang.xdlinkdemo.device.Constants;
import com.xuexiang.xdlinkdemo.device.message.client.ClientJsonResponseMessage;

import java.util.List;

import static com.xuexiang.xdlink.component.message.impl.base.XMessage.MIN_MESSAGE_LENGTH;

/**
 * @author xuexiang
 * @since 2018/9/3 下午11:42
 */
public class ChatClientMessageResolver extends AbstractMessageResolver {

    @Override
    protected int resolveData(byte[] data) throws ResolverException {
        int index = 0;
        if (data.length >= MIN_MESSAGE_LENGTH) { //数据长度足够解析
            List<byte[]> packages = ResolverUtils.getSubPackage(data);
            if (packages == null || packages.size() == 0) return index;

            for (int i = 0; i < packages.size(); i++) {
                index += handlePackageMessage(packages.get(i));
            }
        }
        return index;
    }

    /**
     * 处理消息包
     *
     * @param bytes
     * @return 返回处理消息包的长度
     */
    private int handlePackageMessage(byte[] bytes) {
        switch (bytes[4]) { //第四位是功能码
            case Constants.FunctionCode.CLIENT_JSON_RESPONSE:
                putMessage(new ClientJsonResponseMessage().resolve(bytes));
                break;
            default:
                break;
        }
        return bytes.length;
    }


}
